<?php
include_once "../init.inc.php";
include_once "../inc/header.php";
include_once "../class/pageNavigator.php";

  define("PERPAGE", 5);
  define("OFFSET", "offset");
  





//print_r($_GET);

?>
<script>
    
jQuery("#korzina").text('');
   
   function total(){
       var table=$('#cart_table tr:visible').length-1; 
       
      jQuery("#total").html('<span class="text-info">Total:&nbsp;</span>'+table+'<span class="text-info">&nbsp;items&nbsp;&nbsp;</span>'); 
   };
   
    function clearCart(){
        
        //***********************1
         $.cookie("basket", "", {path: "/"});
                        jQuery("#korzina").html('<div  class="alert alert-info">Your cart is empty</div>');
                        jQuery(".main_table").hide();
                        jQuery("#donloadbtn").hide();
                        jQuery("#total").hide();

    };
    

    
 $(document).ready(function(){ 
     total();
     
       basket = decodeURI($.cookie("basket")); 
               if (basket=='null') {basket = '';}
     var basketArray = basket.split(",");
     var links = $('a.addCart');
     
     links.each(function(index, elem) {
         var msgid = $(this).attr('id');
     
                            for(var i=0; i<basketArray.length-1;i++) {
                                    goodsId = basketArray[i];
                                    if(goodsId == msgid)  // товар уже в корзине
                                    {
                                        //check = true;
                                        //delete basketArray[i];
                                        // break;
                                        $(this).html('<img class="imgcart" src="../images/cart_delete.png">Delete');
                                    }
                                }
     
     
     //  console.log($(this).attr('id'));

     });

      //*********************************************************
     
      $('a.addCart').click(function(){
      data = $(this).attr('id');
      addCart(data);
        var val = $(this).text();
    //console.log(val);
                if (val == "Delete"){
                    $(this).closest('tr').hide();
                       total();
                    basket = decodeURI($.cookie("basket"));
                    //********************************************2
                    if (!basket){
                        jQuery("#korzina").html('<div  class="alert alert-info">Your cart is empty</div>');
                        jQuery(".main_table").hide();
                        jQuery("#donloadbtn").hide();
                        jQuery("#total").hide();

                    }
                    //$(this).html("Add");
                }else{
                   $(this).html("Delete");                 
                };
      return false;
       
     });

    function addCart(p1){
        
     //   alert(p1);
     var msgid;
       msgid = p1;  
        var basket = '';
        var check = false;
        var cnt = false;
        var basketRet;
     
     basket = decodeURI($.cookie("basket"));
     
       if (basket=='null') {basket = '';}
       
       basketArray = basket.split(",");
       for(var i=0; i<basketArray.length-1;i++) {
           goodsId = basketArray[i];
           if(goodsId == msgid || goodsId=="")  // ищем, не покупали ли мы этот товар ранее
           {
               check = true;
               delete basketArray[i];

              // break;
           }
       }
       
    if(!check){
          // basket+= msgid +  ',';
          basketArray += msgid + ',';
    }
     
    basketRet =  $.makeArray(basketArray);
        
        for(var i=0; i<basketRet.length-1;i++) {
          if (basketRet[i]=="" || !(basketRet[i])){
             basketRet.splice(i,1);
             i=0;
          }
          
      }
     
          basketRet = basketRet.join();
          
         
       

           $.cookie("basket", basketRet, {path: "/"});
     
     


    }
    
    
 }) 
    </script>
		


    
    <div id="korzina"><div>

<?php

//****************************************************************************************
//1 берем из кук все ID
//2 составляем sql запрос типа SELECT * FROM `posts` WHERE id IN (1, 2, 10)
//3 выводим его результат


if (@$_COOKIE['basket'])
{ //есть куки с корзиной


$in = getIdFromCookie();   
$sql = "SELECT p.ID, p.post_date, p.post_content, p.post_title, p.prem, p.words, c.cat_name 
        FROM `posts` as p 
        LEFT JOIN `relations` AS r ON p.ID = r.post_id
        LEFT JOIN `category` AS c ON r.cat_id = c.ID
        WHERE p.ID IN ($in)";

 $result = mysql_query($sql) or die('Error, insert query failed');
?>
    <strong id ="total"></strong>
    
<a id="donloadbtn" class="btn btn-success" href="?download=1" onclick="document.forms['dload'].submit();"><i class="icon-arrow-down icon-white"></i>&nbsp;Download</a>
<a  class="btn btn-danger" href="#" onclick="clearCart();return false;"><i class="icon-trash icon-white"></i>&nbsp;Clear the cart</a>
<br />
<br />
<form id="dload" action="" method="get">
           <table id="cart_table" class="main_table">
               <thead>
               <tr>
               <th><i class="icon-shopping-cart"></i>&nbsp;Cart</th>     
               <th><i class="icon-filter"></i>&nbsp;Title</th>
               <th><i class="icon-filter"></i>Words</th>
                           
               </tr>
               </thead>
           
                <?php    while ($row = mysql_fetch_assoc($result)) { ?>
                                    <tr><td><a id="<?php echo $row['ID'];?>" href="#" class="addCart"><img class="imgcart" src="../images/cart_add.png">Add</a></td>
                                        
                    <?php    foreach ($row as $key=>$cellValue){ 
                                        if ($key=="ID" or $key=="prem" or $key=="cat_name" or $key=="post_date" or $key=="post_content") continue;
                                        if ($key=="post_title")  {?>
                                        <td class="left-align">
                                           <a href="<?php echo "viewpost.php?id=".$row['ID']."&amp;cat=$cat&amp;type=$type&amp;search=$search";?>"> 
                                              <?php echo excerpt($cellValue); ?>
                                           </a>
                                        </td>
                                         <?php }else { ?>
                                             <td>
                                           
                                              <?php echo excerpt($cellValue); ?>
                                          
                                             </td>
                                             
                                             
                                       <?php       
                                         }
                                                             
                                                                } 
                                        
                                       ?></tr><?php

                   }   ?>
                                    
           </table><br />
               <?php // <input id ="zagr" type="submit" name="download" value="Загрузить" /> ?>
    </form>

<?php
    
}else{
    echo "<br /> <div class=\"alert alert-info\">Your cart is empty</div>";
}

//*********************************Загрузка********************************************

if (@$_REQUEST['download']){
    
    
    //include_once "../class/download.php";
    
    $id = getIdFromCookie();
    if ($id){
        $id = explode(",", $id);
        
    }else exit;

            $downl = new download($id);

            if ($downl->result){
            echo "<script>
                    $.removeCookie(\"basket\", {path: \"/\"});
                    $('tr').hide();
                    $('input').hide();
                    jQuery(\"#total\").hide();
                    location.href=\"$downl->result\";
                    jQuery(\"#korzina\").html('<div  class=\"alert alert-info\">Your cart is empty</div>');    
                   </script>";    
            echo "<a href=\"$downl->result\">Нажмите сюда, если загрузка не произошла автоматически</a>";
 

            }
       
    
}


//****************************************************************************************

function getIdFromCookie(){
    
    $id = array();
    $id = explode(",", $_COOKIE['basket']);
        foreach ($id as $i){
            if ($i){
        $in .= $i.",";

            }
        }
    if (!$in){
       
        exit;
    }
    $in = substr($in,0,-1);

    return $in;
    
}


function getCol($sql){
    
  $result =  mysql_query("SELECT count(*) as count ".$sql);
    
  $rows = mysql_fetch_assoc($result);
  
  return (int)$rows['count'];
    
    
}




function getCat(){
  
    $cat = array();
    $sql = "SELECT * FROM `category`";
    $result = mysql_query($sql); 
    $ret.= "<option selected value='0'>ALL</option>";
    
        while ($rows = mysql_fetch_assoc($result)){
           $ret.= "<option value=".$rows['ID'].">".$rows['cat_name']."</option>";
            
        }
        
        return $ret;
 
}




?>
<?php include_once 'footer.php'; ?>